package cn.com.se.sharepictrue.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.com.se.sharepictrue.R;
import cn.com.se.sharepictrue.adapter.ShareListAdapter;
import cn.com.se.sharepictrue.application.Data;
import cn.com.se.sharepictrue.bean.HomeShareBean;
import cn.com.se.sharepictrue.business.CallBack;
import cn.com.se.sharepictrue.business.NetworkResponse;
import cn.com.se.sharepictrue.business.ShareApi;
import cn.com.se.sharepictrue.quickadapter.BaseAdapterHelper;
import cn.com.se.sharepictrue.utils.ToastUtils;
import cn.com.se.sharepictrue.widget.LoadMoreListener;

/**
 * Created by Administrator on 2015/12/17.
 */
public class MineLikeActivity extends ActionBarActivity implements ShareListAdapter.ShareItemStatusListener, SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.tb_mine_like_title)
    Toolbar mTbMineLikeTitle;
    @Bind(R.id.ll_mine_like_list)
    ListView mLlMineLikeList;
    @Bind(R.id.srl_mine_like_refresh)
    SwipeRefreshLayout mSrlMineLikeRefresh;
    private List<HomeShareBean> beans;
    private ShareListAdapter mAdapter;

    private LoadMoreListener mLoadMoreListener;
    private final int mLoadInLastRow = 4;
    private int nowPage = 1;
    private static final int REQUEST_CODE_SHARE = 4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_like);
        ButterKnife.bind(this);
        initToolbar();
        initLoadMoreListener();
        initRefreshView();
    }

    private void initToolbar() {
        setSupportActionBar(mTbMineLikeTitle);
        mTbMineLikeTitle.setTitleTextColor(Color.WHITE);
    }

    private void initRefreshView() {
        mSrlMineLikeRefresh.setOnRefreshListener(this);
        mSrlMineLikeRefresh.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);
        mSrlMineLikeRefresh.post(new Runnable() {
            @Override
            public void run() {
                mSrlMineLikeRefresh.setRefreshing(true);
                initList();
            }
        });
    }

    Handler mHandler = new Handler();

    private void initList() {
        nowPage = 1;
        ShareApi.getMyLike(MineLikeActivity.this, nowPage, new CallBack<NetworkResponse<List<HomeShareBean>>>() {
            @Override
            public void onStart() {
                super.onStart();
                mSrlMineLikeRefresh.setRefreshing(true);
            }

            @Override
            public void onFail() {
                mSrlMineLikeRefresh.setRefreshing(false);
                ToastUtils.show(MineLikeActivity.this, "加载失败..");
            }

            @Override
            public void onResponse(NetworkResponse<List<HomeShareBean>> response) {
                mSrlMineLikeRefresh.setRefreshing(false);
                if (!response.isStatus())
                    ToastUtils.show(MineLikeActivity.this, response.getError());
                else {
                    beans = response.getData();
                    initListData();
                }
            }
        });
    }

    private void initListData() {
        if (beans != null && beans.size() > 0) {
            mAdapter = new ShareListAdapter(MineLikeActivity.this, R.layout.item_share_list, beans);
            mAdapter.setShareItemStatusListener(this);
            mLlMineLikeList.setAdapter(mAdapter);
            mLlMineLikeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(MineLikeActivity.this, ShareDetailActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("key", mAdapter.getItem(position));
                    intent.putExtra("item", bundle);
                    intent.putExtra("position", position);
                    startActivityForResult(intent, REQUEST_CODE_SHARE);
                }
            });
            mLlMineLikeList.setOnScrollListener(mLoadMoreListener);
        }
    }

    private void initLoadMoreListener() {
        mLoadMoreListener = new LoadMoreListener(mLoadInLastRow) {
            @Override
            public void load() {
                nowPage++;
                ShareApi.getMyCollection(MineLikeActivity.this, nowPage, new CallBack<NetworkResponse<List<HomeShareBean>>>() {
                    @Override
                    public void onFail() {
                        ToastUtils.show(MineLikeActivity.this, "加载失败..");
                    }

                    @Override
                    public void onResponse(NetworkResponse<List<HomeShareBean>> response) {
                        if (!response.isStatus()) {//加载失败
                            ToastUtils.show(MineLikeActivity.this, response.getError());
                        } else {
                            addToList(response.getData());
                            mLoadMoreListener.setLoading(false);
                        }
                    }
                });
            }
        };
    }

    private void addToList(List<HomeShareBean> data) {
        if (data != null) {
            mAdapter.addAll(data);
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void avatarClick(BaseAdapterHelper helper, HomeShareBean item) {
//ToastUtils.show(mContext,item.toString());
        Intent intent = new Intent(MineLikeActivity.this, PersonalHomepageActivity.class);
        Bundle bundle = new Bundle();
        //bundle.putSerializable(PersonalHomepageActivity.HOMEPAGE_SHAREINFO, item);
        bundle.putString(PersonalHomepageActivity.HOMEPAGE_USERID, item.getUserId());
        bundle.putString(PersonalHomepageActivity.HOMEPAGE_USERNAME, item.getUserName());
        bundle.putString(PersonalHomepageActivity.HOMEPGE_USERPIC, item.getAvatar());
        if (((Data) (MineLikeActivity.this.getApplicationContext())).isLogin() && item.getUserId().contentEquals(((Data) (MineLikeActivity.this.getApplicationContext())).getUserInfo().getUserID()))
            bundle.putString(PersonalHomepageActivity.HOMEPAGE_KEY, PersonalHomepageActivity.HOMEPAGE_ME);
        else
            bundle.putString(PersonalHomepageActivity.HOMEPAGE_KEY, PersonalHomepageActivity.HOMEPAGE_OTHER);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void concernClick(BaseAdapterHelper helper, final HomeShareBean item) {
        String concernId = item.getConcernUserId();
        if (concernId == null) ToastUtils.show(MineLikeActivity.this, "请登录");
        else
            ShareApi.concern(MineLikeActivity.this, item.getUserId(),
                    concernId.equals(HomeShareBean.HOME_SHARE_NO_CONCERN),
                    new CallBack<NetworkResponse<String>>() {
                        @Override
                        public void onFail() {
                            ToastUtils.show(MineLikeActivity.this, "操作失败");
                        }

                        @Override
                        public void onResponse(NetworkResponse<String> response) {
                            if (!response.isStatus())
                                ToastUtils.show(MineLikeActivity.this, response.getError());
                            else {
                                if (item.getConcernUserId().equals(HomeShareBean.HOME_SHARE_NO_CONCERN))
                                    item.setConcernUserId(item.getUserId());
                                else
                                    item.setConcernUserId(HomeShareBean.HOME_SHARE_NO_CONCERN);
                                mAdapter.notifyDataSetChanged();
                            }

                        }
                    });
    }

    @Override
    public void praiseClick(BaseAdapterHelper helper, final HomeShareBean item) {
        String likeIt = item.getPraiseStatus();
        if (likeIt == null) ToastUtils.show(MineLikeActivity.this, "请登录");
        else
            ShareApi.praise(MineLikeActivity.this,
                    item.getShareId(),
                    likeIt.equals(HomeShareBean.HOME_SHARE_NO_PRAISE),
                    new CallBack<NetworkResponse<String>>() {
                        @Override
                        public void onFail() {
                            ToastUtils.show(MineLikeActivity.this, "点赞" + item.getUserName() + "失败");
                        }

                        @Override
                        public void onResponse(NetworkResponse<String> response) {
                            if (!response.isStatus()) {
                                ToastUtils.show(MineLikeActivity.this, response.getError());
                            } else {
                                if (item.getPraiseStatus().equals(HomeShareBean.HOME_SHARE_NO_PRAISE)) {
                                    item.setPraiseStatus(HomeShareBean.HOME_SHARE_IS_PRAISE);
                                    item.setPraiseNum(item.getPraiseNum() + 1);
                                } else {
                                    item.setPraiseStatus(HomeShareBean.HOME_SHARE_NO_PRAISE);
                                    item.setPraiseNum(item.getPraiseNum() - 1);
                                }

                                mAdapter.notifyDataSetChanged();
                            }
                        }
                    });
    }

    @Override
    public void collectionClick(BaseAdapterHelper helper, final HomeShareBean item) {
        String favorite = item.getFavoriteStatus();
        if (favorite == null) ToastUtils.show(MineLikeActivity.this, "请登录");
        else
            ShareApi.favorite(MineLikeActivity.this,
                    item.getShareId(),
                    favorite.equals(HomeShareBean.HOME_SHARE_NO_FAVORITE),
                    new CallBack<NetworkResponse<String>>() {
                        @Override
                        public void onFail() {
                            ToastUtils.show(MineLikeActivity.this, "操作失败");
                        }

                        @Override
                        public void onResponse(NetworkResponse<String> response) {
                            if (!response.isStatus())
                                ToastUtils.show(MineLikeActivity.this, response.getError());
                            else {
                                if (item.getFavoriteStatus().equals(HomeShareBean.HOME_SHARE_NO_FAVORITE))
                                    item.setFavoriteStatus(HomeShareBean.HOME_SHARE_IS_FAVORITE);
                                else
                                    item.setFavoriteStatus(HomeShareBean.HOME_SHARE_NO_FAVORITE);
                                mAdapter.notifyDataSetChanged();
                            }

                        }
                    });
    }

    @Override
    public void commentClick(BaseAdapterHelper helper, HomeShareBean item) {
        Intent intent = new Intent(MineLikeActivity.this, ShareDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("key", item);
        intent.putExtra("item", bundle);
        intent.putExtra("position", helper.getPosition());
        startActivityForResult(intent, REQUEST_CODE_SHARE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        HomeShareBean item = null;
        int position = -1;
        if (requestCode == REQUEST_CODE_SHARE && resultCode == Activity.RESULT_OK) {
            Log.d("xxxxxxxxxxxxxx", "return ok");
            if (data != null) {
                Bundle bundle = data.getBundleExtra("item");
                if (bundle != null)
                    item = (HomeShareBean) bundle.getSerializable("key");
                position = data.getIntExtra("position", -1);
            }
            if (item != null) Log.d("sssssss", item.toString());
            if (item != null && position != -1 && mAdapter.getCount() > position) {
                mAdapter.set(position, item);
            }
        }
    }

    @Override
    public void onRefresh() {
        initList();
    }
}
